package com.jmuok.web.fff.web.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("userDetailsService")
public class FFFUserDetailsService implements UserDetailsService {

	private static final Log logger = LogFactory
			.getLog(FFFUserDetailsService.class);

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		if (logger.isDebugEnabled()) {
			logger.debug("UserDetails: " + username + " is loading...");
		}
		com.jmuok.web.fff.domain.User user = com.jmuok.web.fff.domain.User
				.findUsersByUserNameOrEmail(username).getSingleResult();
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		authorities.add(new SimpleGrantedAuthority("ROLE_"
				+ user.getRoleId().getName()));
		User springUser = new User(user.getUserName(), user.getPassword(),
				user.getAccountEnabled(), !user.getAccountExpired(),
				!user.getCredentialsExpired(), !user.getAccountLocked(),
				authorities);
		if (logger.isDebugEnabled()) {
			logger.debug("UserDetails: " + username + " loaded.");
			logger.debug(springUser);
		}
		return springUser;
	}
}
